<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java 8 Stream API详解( 一)——基本概念, 码道诚公">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="baidu-site-verification" content="code-oqVlgh2wQV" />
    <meta name="google-site-verification" content="Z-8Fm46WY6NL_3kxilmoqToW4jnvyF7boTgciTLBXUs" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Java 8 Stream API详解( 一)——基本概念 | 码道诚公</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="码道诚公" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">码道诚公</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">码道诚公</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Java 8 Stream API详解( 一)——基本概念</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="container content">

    
    <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java-Stream/">
                                <span class="chip bg-color">Java Stream</span>
                            </a>
                        
                            <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                                <span class="chip bg-color">函数式</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                            <a href="/categories/Java/Stream/" class="post-category">
                                Stream
                            </a>
                        
                            <a href="/categories/Java/Stream/%E5%87%BD%E6%95%B0%E5%BC%8F/" class="post-category">
                                函数式
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-01-18
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    15 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>本系列主要用于记录关于Stream API的一些学习笔记，用于自己以后复习，也希望可以帮助到其他人。<br>本文主要记录一些基本概念，后面会记录一些常用的流操作和API案例。</p>
<ul>
<li><a href="/posts/da7966d.html" title="基本概念">基本概念</a></li>
<li><a href="/posts/9739b154.html" title="流收集器">流收集器</a></li>
<li><a href="/posts/108cf37c.html" title="流操作">流操作</a>

</li>
</ul>
<h2 id="Stream创建"><a href="#Stream创建" class="headerlink" title="Stream创建"></a><strong>Stream创建</strong></h2><p>有许多方法可以创建不同源的流实例。一旦创建，实例将不会修改它的源，因此允许从一个源创建多个实例。</p>
<h3 id="空Stream"><a href="#空Stream" class="headerlink" title="空Stream"></a>空Stream</h3><p>在创建空流时，应该使用empty()方法：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamEmpty <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">empty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>通常情况下，在创建流时使用empty()方法来避免对没有元素的流返回null：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> <span class="token function">streamOf</span><span class="token punctuation">(</span>List<span class="token operator">&lt;</span>String<span class="token operator">></span> list<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> list <span class="token operator">==</span> null <span class="token operator">||</span> list<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">?</span> Stream<span class="token punctuation">.</span><span class="token function">empty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<h3 id="集合Stream"><a href="#集合Stream" class="headerlink" title="集合Stream"></a>集合Stream</h3><p>可以依据任何类型的集合(Collection，List，Set)来创建流：</p>
<pre class=" language-java"><code class="language-java">Collection<span class="token operator">&lt;</span>String<span class="token operator">></span> collection <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfCollection <span class="token operator">=</span> collection<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="数组Stream"><a href="#数组Stream" class="headerlink" title="数组Stream"></a>数组Stream</h3><p>数组也可以是Stream的源：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfArray <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>也可以依据现有数组或数组的一部分来创建流：</p>
<pre class=" language-java"><code class="language-java">String<span class="token punctuation">[</span><span class="token punctuation">]</span> arr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfArrayFull <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfArrayPart <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="Stream-builder"><a href="#Stream-builder" class="headerlink" title="Stream.builder()"></a><strong>Stream.builder()</strong></h3><p>当使用builder时，应该指定所需的类型，否则build()方法将创建_Stream<object>_的实例：</object></p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamBuilder <span class="token operator">=</span> Stream<span class="token punctuation">.</span>&lt;String<span class="token operator">></span><span class="token function">builder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token string">"a"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token string">"b"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token string">"c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="Stream-generate"><a href="#Stream-generate" class="headerlink" title="Stream.generate()"></a><strong>Stream.generate()</strong></h3><p>generate()方法接受Supplier<t>来生成元素。由于产生的流是无限的，开发人员应该显式指定所需的大小，否则generate()方法将一直工作，直到超出内存限制：</t></p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamGenerated <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">generate</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> <span class="token string">"element"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>上面的代码会生成包含10个字符串“element”的序列。</p>
<h3 id="Stream-iterate"><a href="#Stream-iterate" class="headerlink" title="Stream.iterate()"></a><strong>Stream.iterate()</strong></h3><p>创建无限流的另一种方法是使用iterate()方法：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>Integer<span class="token operator">></span> streamIterated <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">iterate</span><span class="token punctuation">(</span><span class="token number">40</span><span class="token punctuation">,</span> n <span class="token operator">-</span><span class="token operator">></span> n <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>函数的第一个参数就是结果Stream中的第一个元素，后面每个元素都是使用给定的函数结合上一个元素计算得出的。在上面的例子中，第二个元素就是42。</p>
<h3 id="基本类型Stream"><a href="#基本类型Stream" class="headerlink" title="基本类型Stream"></a>基本类型Stream</h3><p>Java 8提供了从三种基本类型（int，long和double）中创建流的方式。 由于Stream <t>是泛型接口，无法将基本类型用作泛型的类型参数，因此创建了三个新的特殊接口：IntStream，LongStream和DoubleStream。<br>使用新接口减少了不必要的自动装箱，从而提高了效率：</t></p>
<pre class=" language-java"><code class="language-java">IntStream intStream <span class="token operator">=</span> IntStream<span class="token punctuation">.</span><span class="token function">range</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
LongStream longStream <span class="token operator">=</span> LongStream<span class="token punctuation">.</span><span class="token function">rangeClosed</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p><strong><em>range(int startInclusive, int endExclusive)</em></strong> 方法会创建一个从第一个参数到第二个参数的有序流，该方法以步长为1逐步增加后续元素的值。最终的结果Stream中不包含第二个参数，该参数只用于表示序列的上界。<br>_**rangeClosed(int startInclusive, int endInclusive) **_方法作用是相同的，只有一点区别——结果Stream中包含第二个参数。这两个方法可以用于生成基本类型的流。<br>从Java 8开始，Random类为生成基本类型流提供了一些方法。例如，以下代码创建一个DoubleStream，其中包含三个元素：</p>
<pre class=" language-java"><code class="language-java">Random random <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
DoubleStream doubleStream <span class="token operator">=</span> random<span class="token punctuation">.</span><span class="token function">doubles</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="字符串Stream"><a href="#字符串Stream" class="headerlink" title="字符串Stream"></a>字符串Stream</h3><p>字符串也可以作为创建流的源。<br>通过使用String类中的chars()方法可以得到一个字符流。由于JDK中没有定义_CharStream_接口，可以使用_IntStream_来代替字符流。</p>
<pre class=" language-java"><code class="language-java">IntStream streamOfChars <span class="token operator">=</span> <span class="token string">"abc"</span><span class="token punctuation">.</span><span class="token function">chars</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>下面的示例根据指定的RegEx将String拆分为子字符串：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfString <span class="token operator">=</span> Pattern<span class="token punctuation">.</span><span class="token function">compile</span><span class="token punctuation">(</span><span class="token string">", "</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">splitAsStream</span><span class="token punctuation">(</span><span class="token string">"a, b, c"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="文件Stream"><a href="#文件Stream" class="headerlink" title="文件Stream"></a>文件Stream</h3><p>Java NIO类_Files_允许通过_lines()_方法生成文本文件对应的_Stream<string>_，文本的每一行都是结果Stream中的一个元素：</string></p>
<pre class=" language-java"><code class="language-java">Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"C:\\file.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamOfStrings <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">lines</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> streamWithCharset <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">lines</span><span class="token punctuation">(</span>path<span class="token punctuation">,</span> Charset<span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>可以将_Charset_指定为_lines()_方法的参数。</p>
<h2 id="Stream引用"><a href="#Stream引用" class="headerlink" title="Stream引用"></a>Stream引用</h2><p>只要仅调用中间操作，就可以实例化流并得到可访问的引用。 执行终结操作会使流不可访问。<br>为了证明这一点，我们先暂时忘记最佳实践是链接操作序列。 除了不必要的冗长之外，从技术上讲，以下代码是有效的：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> stream <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> element<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span><span class="token string">"b"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Optional<span class="token operator">&lt;</span>String<span class="token operator">></span> anyElement <span class="token operator">=</span> stream<span class="token punctuation">.</span><span class="token function">findAny</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>但是，在调用终结操作之后尝试重用相同的引用将触发_IllegalStateException_：</p>
<pre class=" language-java"><code class="language-java">Optional<span class="token operator">&lt;</span>String<span class="token operator">></span> firstElement <span class="token operator">=</span> stream<span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>由于IllegalStateException是RuntimeException，编译器也就不会发现该问题。 因此，记住<strong>Java 8中流不可重用</strong>是非常重要的。<br>这种行为是合乎逻辑的，因为流的设计目的是提供一种能力，以函数式风格将有限的操作序列应用到数据源，但是其本身并不存储元素。<br>因此，为使先前的代码正常工作，应进行一些更改：</p>
<pre class=" language-java"><code class="language-java">List<span class="token operator">&lt;</span>String<span class="token operator">></span> elements <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> element<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span><span class="token string">"b"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Optional<span class="token operator">&lt;</span>String<span class="token operator">></span> anyElement <span class="token operator">=</span> elements<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">findAny</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Optional<span class="token operator">&lt;</span>String<span class="token operator">></span> firstElement <span class="token operator">=</span> elements<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h2 id="Stream-Pipeline"><a href="#Stream-Pipeline" class="headerlink" title="Stream Pipeline"></a>Stream Pipeline</h2><p>要在数据源的元素上执行一系列操作并聚合其结果，需要三个部分:源、中间操作和终结操作。<br>中间操作会返回新的修改后的流。 例如，要创建一个现有流的新流而摒除其中的几个元素，则可以使用_skip()_方法：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> onceModifiedStream <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">"abcd"</span><span class="token punctuation">,</span> <span class="token string">"bbcd"</span><span class="token punctuation">,</span> <span class="token string">"cbcd"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>如果需要多个修改操作，可以链式串接多个中间操作。假设我们还需要将当前Stream <string>的每个元素替换为由前几个字符组成的子字符串。 可以通过链接_skip()_和_map()_方法来完成：</string></p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> twiceModifiedStream <span class="token operator">=</span> stream<span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> element<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>可以看到，_map()_方法可以接收一个lambda表达式作为参数。<br>流本身是没有价值的，用户真正感兴趣的是终结操作的结果，终结操作可以是某种类型的值，也可以是应用于流的每个元素的操作。<strong>每个流只能使用一个终结操作</strong>。<br>使用流的正确和最方便的方法是通过流管道，流管道是流数据源、中间操作和终结操作组成的链式操作。例如：</p>
<pre class=" language-java"><code class="language-java">List<span class="token operator">&lt;</span>String<span class="token operator">></span> list <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">"abc1"</span><span class="token punctuation">,</span> <span class="token string">"abc2"</span><span class="token punctuation">,</span> <span class="token string">"abc3"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">long</span> size <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> element<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h2 id="延迟调用"><a href="#延迟调用" class="headerlink" title="延迟调用"></a>延迟调用</h2><p><strong>中间操作是惰性的。</strong>这意味着<strong>只有在执行终端操作时才需要调用它们</strong>。<br>为了演示这一点，假设我们有一个方法_wasCalled()_，每次调用它时都会对内部计数器进行加一操作：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">long</span> counter<span class="token punctuation">;</span>

<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">wasCalled</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    counter<span class="token operator">++</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>我们可以通过_filter()_操作来调用_wasCalled()_方法：</p>
<pre class=" language-java"><code class="language-java">List<span class="token operator">&lt;</span>String<span class="token operator">></span> list <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>“abc1”<span class="token punctuation">,</span> “abc2”<span class="token punctuation">,</span> “abc3”<span class="token punctuation">)</span><span class="token punctuation">;</span>
counter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
Stream<span class="token operator">&lt;</span>String<span class="token operator">></span> stream <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
        <span class="token function">wasCalled</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> element<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>因为我们的数据源中有三个元素，我们可以推测_filter()_方法会调用三次，而_counter_变量的值会是3。但是运行代码的结果并没有改变_counter_，它的值仍然是0。因此，_filter()_方法一次都没有被调用过，原因就是——缺少终结操作。<br>我们来稍微重写一下这段代码，添加一个map()操作和一个终结操作——findFirst()，通过添加日志方便我们确认方法的执行顺序：</p>
<pre class=" language-java"><code class="language-java">Optional<span class="token operator">&lt;</span>String<span class="token operator">></span> stream <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"filter() was called"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> element<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"map() was called"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> element<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>结果日志显示，_filter()_方法被调用了两次，_map()_方法只被调用了一次。之所以如此，是因为管道是垂直执行的。在我们的示例中，流中的第一个元素不满足filter的断言，然后对第二个元素执行filter()方法，而且该元素满足断言。接下来我们没有为第三个元素调用_filter()_方法，而是让第二个元素通过管道到达_map()_方法。<br>仅需要一个元素就可以满足findFirst()方法，因此，在这个特定的例子中，惰性执行可以避免两个方法的调用：_filter()_方法和_map()_方法。</p>
<h2 id="执行顺序"><a href="#执行顺序" class="headerlink" title="执行顺序"></a>执行顺序</h2><p>从性能的角度来看，<strong>正确的顺序是流管道中链式操作最重要的考察方面之一</strong>：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">long</span> size <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
        <span class="token function">wasCalled</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> element<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>执行此代码会将计数器的值加3，这表明该流的_map()_方法被调用了三次，但是size的值是1。也就是说，结果流中只有一个元素，我们无缘无故地多执行了两次_map()_操作。<br>如果我们更改_skip()_和_map()_方法的顺序，计数器只会增加1，说明_map()_方法只被调用了一次：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">long</span> size <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>element <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
        <span class="token function">wasCalled</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> element<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>由此引出一个规则：能够减少流大小的中间操作应该放在应用于流中元素的操作之前，因此，在流管道中应该把_skip()_、_filter()_、_distinct()_放在顶部。</p>
<h2 id="Stream-Reduction"><a href="#Stream-Reduction" class="headerlink" title="Stream Reduction"></a>Stream Reduction</h2><p>API中有很多终结操作可以将流聚合为一个类或一个基本类型。例如，_count()、max()、min()、sum()_，但是这些操作是根据预定义的实现而工作的。如果开发人员需要自定义流的归集机制呢？有两个方法可以实现：_reduce()_和_collect()_方法。</p>
<h3 id="reduce-方法"><a href="#reduce-方法" class="headerlink" title="reduce()方法"></a>reduce()方法</h3><p>该方法有三个变体，区别在于其签名和返回类型。方法可以接收下列参数：<br><strong>identity</strong>——累加器的初始值，或者当流数据为空无法累加时返回的默认值；<br><strong>accumulator</strong>——指定聚合元素逻辑的函数。由于累加器对每一步操作都会创建新值，新值的数量等于流的大小，只有最后一个值是有用的。这对于性能不是很好。<br><strong>combiner</strong>——聚合累加器结果的函数。Combiner仅在并行模式下调用，以汇总来自不同线程的累加器的结果。<br>我们来看一下这三个方法：</p>
<pre class=" language-java"><code class="language-java">OptionalInt reduced <span class="token operator">=</span> IntStream<span class="token punctuation">.</span><span class="token function">range</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> a <span class="token operator">+</span> b<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>结果为： _reduced _= 6 (1 + 2 + 3)</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">int</span> reducedTwoParams <span class="token operator">=</span> IntStream<span class="token punctuation">.</span><span class="token function">range</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> a <span class="token operator">+</span> b<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>结果为：<em>reducedTwoParams</em> = 16 (10 + 1 + 2 + 3)</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">int</span> reducedParams <span class="token operator">=</span> Stream<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> 
            <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> a <span class="token operator">+</span> b<span class="token punctuation">,</span> 
            <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
                 log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"combiner was called"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                 <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
              <span class="token punctuation">}</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>结果与前面的示例相同（16），并且没有日志输出，表明combiner没有被调用。要想使combiner生效，流需要是并行化的：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">int</span> reducedParallel <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">parallelStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> 
            <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> a <span class="token operator">+</span> b<span class="token punctuation">,</span> 
            <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span>
                   log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"combiner was called"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                   <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>这里的结果是不同的（36）而且combiner被调用了两次，这里的归集过程是通过以下算法进行的：累加器运行了三次，将流中的每个元素都增加了identity。这些操作是并行的，因此结果为（10 + 1 = 11; 10 + 2 = 12; 10 + 3 = 13;）。之后，combiner会合并这三个结果，需要进行两次迭代操作（12 + 13 = 25; 25 + 11 = 36）。</p>
<h3 id="collect-方法"><a href="#collect-方法" class="headerlink" title="collect()方法"></a>collect()方法</h3><p>流的归集也可以通过另一个终结操作来完成——collect()方法。它接收一个Collector类型的参数，该参数会声明数据归集机制。系统已经为大多数的常见操作创建了预定义的收集器，可以通过Collectors类的帮助来访问这些方法。<br>在这一小节，我们使用下面的List作为整个流的数据源：</p>
<pre class=" language-java"><code class="language-java">List<span class="token operator">&lt;</span>Product<span class="token operator">></span> productList <span class="token operator">=</span> Arrays<span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>
    <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token number">23</span><span class="token punctuation">,</span> <span class="token string">"potatoes"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
      <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token number">14</span><span class="token punctuation">,</span> <span class="token string">"orange"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> 
    <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token number">13</span><span class="token punctuation">,</span> <span class="token string">"lemon"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
      <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token number">23</span><span class="token punctuation">,</span> <span class="token string">"bread"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> 、
    <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token number">13</span><span class="token punctuation">,</span> <span class="token string">"sugar"</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>将流转换为集合（<strong><em>Collection, List <em>or</em> Set</em></strong>）：</p>
<pre class=" language-java"><code class="language-java">List<span class="token operator">&lt;</span>String<span class="token operator">></span> collectorCollection <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>归集为<strong><em>String</em></strong>：</p>
<pre class=" language-java"><code class="language-java">String listToString <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">joining</span><span class="token punctuation">(</span><span class="token string">", "</span><span class="token punctuation">,</span> <span class="token string">"["</span><span class="token punctuation">,</span> <span class="token string">"]"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>joiner()方法可以接收一到三个参数（delimiter, prefix, suffix），分别表示分隔符、前缀和后缀。使用joiner()方法最方便的地方在于——开发者不需要检查流是否已经结束，以决定要使用分隔符还是后缀。Collector会对其进行处理。<br>计算流中所有数字元素的平均值：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">double</span> averagePrice <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">averagingInt</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getPrice<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>计算流中所有数字元素的总和：</p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">int</span> summingPrice <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">summingInt</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getPrice<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p><em>averagingXX(), summingXX()</em> 和 _summarizingXX()_三个方法可以处理基本类型（int、long、double）及其包装类型（Integer、Long和Double）。这些方法有一个更强大的特性是提供映射操作，这样开发者就不需要在_collect()_之前执行额外的_map()_操作了。<br>收集流元素的统计信息：</p>
<pre class=" language-java"><code class="language-java">IntSummaryStatistics statistics <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">summarizingInt</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getPrice<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>通过使用返回的<em>IntSummaryStatistics_实例，开发者可以调用其toString()方法来创建一个统计报告，结果是一个字符串，其格式类似：_“IntSummaryStatistics{count=5, sum=86, min=13, average=17,200000, max=23}”。</em><br>_通过应用其中的方法getCount(), getSum(), getMin(), getAverage(), getMax()_可以分别获得对应的统计信息，所有这些值都可以从一个管道中提取。<br>根据指定函数对流中元素进行分组：</p>
<pre class=" language-java"><code class="language-java">Map<span class="token operator">&lt;</span>Integer<span class="token punctuation">,</span> List<span class="token operator">&lt;</span>Product<span class="token operator">>></span> collectorMapOfLists <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">groupingBy</span><span class="token punctuation">(</span>Product<span class="token operator">:</span><span class="token operator">:</span>getPrice<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>上面的示例中，流被归集为一个按照价格对产品进行分组的Map。<br>根据断言将流中元素分类：</p>
<pre class=" language-java"><code class="language-java">Map<span class="token operator">&lt;</span>Boolean<span class="token punctuation">,</span> List<span class="token operator">&lt;</span>Product<span class="token operator">>></span> mapPartioned <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>
        Collectors<span class="token punctuation">.</span><span class="token function">partitioningBy</span><span class="token punctuation">(</span>
            element <span class="token operator">-</span><span class="token operator">></span> element<span class="token punctuation">.</span><span class="token function">getPrice</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">15</span>
        <span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>推动Collector执行额外转换操作：</p>
<pre class=" language-java"><code class="language-java">Set<span class="token operator">&lt;</span>Product<span class="token operator">></span> unmodifiableSet <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>
        Collectors<span class="token punctuation">.</span><span class="token function">collectingAndThen</span><span class="token punctuation">(</span>
            Collectors<span class="token punctuation">.</span><span class="token function">toSet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            Collections<span class="token operator">:</span><span class="token operator">:</span>unmodifiableSet
        <span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>在这个例子中，Collector将流转换为Set，然后在其基础上创建了一个不可修改的Set。<br>自定义Collector：<br>如果出于某些原因，需要自定义一个Collector，那么最容易最简单的方法就是使用Collector类的_of()_方法：</p>
<pre class=" language-java"><code class="language-java">Collector<span class="token operator">&lt;</span>Product<span class="token punctuation">,</span> <span class="token operator">?</span><span class="token punctuation">,</span> LinkedList<span class="token operator">&lt;</span>Product<span class="token operator">>></span> toLinkedList <span class="token operator">=</span> 
    Collector<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>
        LinkedList<span class="token operator">:</span><span class="token operator">:</span><span class="token keyword">new</span><span class="token punctuation">,</span> 
        LinkedList<span class="token operator">:</span><span class="token operator">:</span>add<span class="token punctuation">,</span> 
        <span class="token punctuation">(</span>first<span class="token punctuation">,</span> second<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{</span> 
               first<span class="token punctuation">.</span><span class="token function">addAll</span><span class="token punctuation">(</span>second<span class="token punctuation">)</span><span class="token punctuation">;</span> 
               <span class="token keyword">return</span> first<span class="token punctuation">;</span> 
        <span class="token punctuation">}</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>

LinkedList<span class="token operator">&lt;</span>Product<span class="token operator">></span> linkedListOfPersons <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>toLinkedList<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>这个例子中，最终会得到一个_LinkedList<product>_。</product></p>
<h2 id="并行流"><a href="#并行流" class="headerlink" title="并行流"></a>并行流</h2><p>在Java8之前，并行化很复杂。ExecutorService和ForkJoin的出现简化了开发人员的工作，但他们仍需要关注如何创建特定的Executor，以及如何运行它等等。 Java 8中引入了一种以函数式风格实现并行的方法。<br>该API可用于创建并行流，以并行模式执行操作。当流的数据源是集合或数组时，可以借助<strong><em>parallelStream()</em></strong> 方法实现：</p>
<pre class=" language-java"><code class="language-java">Stream<span class="token operator">&lt;</span>Product<span class="token operator">></span> streamOfCollection <span class="token operator">=</span> productList<span class="token punctuation">.</span><span class="token function">parallelStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> isParallel <span class="token operator">=</span> streamOfCollection<span class="token punctuation">.</span><span class="token function">isParallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> bigPrice <span class="token operator">=</span> streamOfCollection
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>product <span class="token operator">-</span><span class="token operator">></span> product<span class="token punctuation">.</span><span class="token function">getPrice</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">12</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">anyMatch</span><span class="token punctuation">(</span>price <span class="token operator">-</span><span class="token operator">></span> price <span class="token operator">></span> <span class="token number">200</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>如果流的数据源不是集合或数组，应该使用<strong><em>parallel()</em></strong> 方法：</p>
<pre class=" language-java"><code class="language-java">IntStream intStreamParallel <span class="token operator">=</span> IntStream<span class="token punctuation">.</span><span class="token function">range</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">150</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">parallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> isParallel <span class="token operator">=</span> intStreamParallel<span class="token punctuation">.</span><span class="token function">isParallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>在底层，Stream API会自动通过ForkJOIN框架并发执行操作。默认情况下，会使用公共线程池，而且无法（至少目前是这样）为其分配自定义的线程池。可以使用自定义的<a target="_blank" rel="noopener" href="https://github.com/pivovarit/parallel-collectors">并行Collector</a>来解决这个问题。<br>在并行模式下使用流时，要避免阻塞操作；尽量在执行任务的耗时接近时使用并发模式（如果某个任务耗时比其它任务长很多，它会拖慢整个应用中的工作流）。<br>通过使用_sequential()_方法可以将并行模式的流转换回串行模式：</p>
<pre class=" language-java"><code class="language-java">IntStream intStreamSequential <span class="token operator">=</span> intStreamParallel<span class="token punctuation">.</span><span class="token function">sequential</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> isParallel <span class="token operator">=</span> intStreamSequential<span class="token punctuation">.</span><span class="token function">isParallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>Stream API是一组功能强大但易于理解的处理元素序列的工具。它帮助我们减少大量的样板代码，创建更可读的程序，并提高应用程序的工作效率。<br>在本文中显示的大多数代码示例中，流都没有被使用(我们没有应用close()方法或终端操作)。在实际应用中，不要让一个实例化的流未被使用，因为这会导致内存泄漏。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Guo Yaxiang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.codinghonest.space/posts/da7966d.html">https://www.codinghonest.space/posts/da7966d.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Guo Yaxiang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java-Stream/">
                                    <span class="chip bg-color">Java Stream</span>
                                </a>
                            
                                <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                                    <span class="chip bg-color">函数式</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    
        <style>
    .mvaline-card {
        margin: 1.5rem auto;
    }

    .mvaline-card .card-content {
        padding: 20px 20px 5px 20px;
    }
</style>

<div class="card mvaline-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="mvcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/minivaline/MiniValine.js"></script>
<script>
    new MiniValine({
        el: '#mvcomments',
        appId: 'oqAo7rCWejwTqHjGC2APTVDX-MdYXbMMI',
        appKey: 'pfyY919tO7iJaDm7lFmvh5Wp',
        mode: 'DesertsP',
        placeholder: 'Write a Comment',
        pathname: window.location.pathname,
        lang: '',
        adminEmailMd5: '8BBC105436DAAF8C803841C8FD13CD0C',
        tagMeta: ["管理员", "小伙伴", "访客"],
        master: ["8BBC105436DAAF8C803841C8FD13CD0C"],
        friends: ["FA21C7921CD42FE9523E957870873F64", "586BAB41BB5692877F7714DFE4947DEC"],
        math: true,
        md: true,
        enableQQ: false,
        NoRecordIP: false,
        visitor: true,
        maxNest: 6,
        pageSize: 6,
        serverURLs: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest", "https://cdn.jsdelivr.net/gh/MiniValine/qq@latest", "https://cdn.jsdelivr.net/gh/MiniValine/Bilibilis@latest", "https://cdn.jsdelivr.net/gh/MiniValine/tieba@latest", "https://cdn.jsdelivr.net/gh/MiniValine/twemoji@latest", "https://cdn.jsdelivr.net/gh/MiniValine/weibo@latest"],
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/9739b154.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/4.jpg" class="responsive-img" alt="Java 8 Stream API详解( 二)——Stream Collectors">
                        
                        <span class="card-title">Java 8 Stream API详解( 二)——Stream Collectors</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本系列主要用于记录关于Stream API的一些学习笔记，用于自己以后复习，也希望可以帮助到其他人。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-01-18
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            <a href="/categories/Java/Stream/" class="post-category">
                                    Stream
                                </a>
                            
                            <a href="/categories/Java/Stream/%E5%87%BD%E6%95%B0%E5%BC%8F/" class="post-category">
                                    函数式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java-Stream/">
                        <span class="chip bg-color">Java Stream</span>
                    </a>
                    
                    <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                        <span class="chip bg-color">函数式</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/1e489de2.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/11.jpg" class="responsive-img" alt="分布式系统中的命令与事件">
                        
                        <span class="card-title">分布式系统中的命令与事件</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            尽管分布式系统设计可能很复杂，但它们也可以归结为一些基本概念，其中一个重要的概念是命令和事件之间的区别。几乎每个微服务之间的所有交互都涉及这两个概念。如果我们能够识别出一个给定的用例是否包含命令处理或事件处理，我们就可以得到与系统其余部分一致的可靠设计。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-11-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/" class="post-category">
                                    分布式系统
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/">
                        <span class="chip bg-color">分布式系统</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 码道诚公<br />'
            + '文章作者: Guo Yaxiang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Guo Yaxiang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/GuoYaxiang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:YXGyxg112358@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1431800679" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1431800679" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/guo-ya-xiang" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/guo-ya-xiang" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    
        <script src="//code.tidio.co/zgiqinzrat1rzwxseqhr2pnzsp2a4rjo.js"></script>
        <script>
            $(document).ready(function () {
                setInterval(change_Tidio, 50);
                function change_Tidio() {
                    var tidio=$("#tidio-chat iframe");
                    if(tidio.css("display")=="block"&& $(window).width()>977 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"85px":"20px";
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                        document.getElementById("tidio-chat-iframe").style.zIndex="998";
                    }
                }
            });
        </script>
    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
